<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="fn(change)">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="item.id">
          <td>{{ index + 1 }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="delFn(item.id)">删除</button>
            <button @click="editFn(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 判断按键功能
      change: -1,
      uname: '',
      age: '',
      gender: '男',
      list: JSON.parse(localStorage.getItem('list-score')) || [],
    }
  },
  methods: {
    fn(change) {
      if (this.uname === '' || this.age === '') {
       return alert('输入选项不能为空')       
      }
      if (change === -1) {
        // 添加
        this.list.push({
          id: this.list.length ? this.list.at(-1).id + 1 : 1,
          uname: this.uname,
          age: this.age,
          gender: this.gender,
        })
      } else {
        // 编辑
        this.list[change].uname = this.uname
        this.list[change].age = this.age
        this.list[change].gender = this.gender
        this.change = -1
      }
      this.uname = ''
      this.age = ''
      this.gender = '男'
    },
      // 回显
    editFn(index) {
      this.change = index
        this.uname = this.list[index].uname
        this.age = this.list[index].age
      this.gender = this.list[index].gender
    },
    // 删除
    delFn(id) {
      this.list = this.list.filter((item) => item.id !== id)
    },
  },
  // 监听list 更新储存本地
  watch: {
    list() {
      localStorage.setItem('list-score', JSON.stringify(this.list))
    },
  },
}
</script>
